//
//  ErandReportViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-21.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "ErandReportViewController.h"
#import "HistoryProblemDetailViewController.h"
#import "MTStatusBarOverlay.h"

@interface ErandReportViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *segLeftImgV;
@property (weak, nonatomic) IBOutlet UILabel *segLeftLbl;
@property (weak, nonatomic) IBOutlet UIButton *segLeftBtn;

@property (weak, nonatomic) IBOutlet UIImageView *segRightImgV;
@property (weak, nonatomic) IBOutlet UILabel *segRightLbl;
@property (weak, nonatomic) IBOutlet UIButton *segRightBtn;
@property (weak, nonatomic) IBOutlet UIButton *submitReportBtn;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *historyProblemList; //历史未完成问题
@property (nonatomic, strong) NSMutableArray *problemList; //本次临店问题
@property (nonatomic, assign) NSInteger segmentIndex; //当前选中的segment标识

- (IBAction)selectSegmentAction:(id)sender;
- (IBAction)submitReportAction:(id)sender;

@end

@implementation ErandReportViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.historyProblemList = [NSMutableArray array];
    self.problemList = [NSMutableArray array];
    
    self.navigationController.navigationBarHidden = NO;
    
    self.segmentIndex = 2;
    
    UserInfo *user = [UserInfo instance];
    NSInteger roleFlag = [[user.info objectForKeyOrNil:@"ryfl"] integerValue];
    if (roleFlag == 2) {
        self.submitReportBtn.hidden = YES;
    } else {
        self.submitReportBtn.hidden = NO;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    self.title = @"出差报告";
    self.showLeftBtn = YES;
    self.showRightBtn = NO;
    [super viewWillAppear:animated];
    
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    
    [self performSelector:@selector(refreshViewByReloadData) withObject:nil afterDelay:0.3];
    
}

- (void)refreshViewByReloadData {
    if (self.segmentIndex == 1) {
        [self setSegmentStatusWithIndex:100];
    } else {
        [self setSegmentStatusWithIndex:101];
    }
}

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)selectSegmentAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    NSInteger tag = btn.tag;
    
    [self setSegmentStatusWithIndex:tag];
}

- (IBAction)submitReportAction:(id)sender {
    
    BOOL canSumit = YES;
    if ([self.problemList count] > 0) {
        for (NSDictionary *cellData in self.problemList) {
            NSString *endtime = [cellData objectForKeyOrNil:@"sjz"]; //截止时间
            if ([endtime length] == 0) {
                canSumit = NO;
                break;
            }
        }
    }
    
    if (!canSumit) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"时间截止必须全部存在才能提交"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else {
        NSString *pc = [self.applyInfo objectForKeyOrNil:@"pc"];
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               pc,@"pc",
                               gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:generateReport parameter:param delegate:self];
        [self.HUD show:YES];
    }
    
}

- (void)setSegmentStatusWithIndex:(NSInteger)index {
    if (!self.isRefreshing) {
        if (index == 100) { //历史未完成问题
            
            self.segmentIndex = 1;
            
            self.segLeftImgV.image = [UIImage imageNamed:@"筛选btn_左_p.png"];
            self.segLeftLbl.textColor = [UIColor whiteColor];
            self.segRightImgV.image = [UIImage imageNamed:@"筛选btn_右_n.png"];
            self.segRightLbl.textColor = CustomRed;
            
            [self getHistoryProblemList];
            
        } else if (index == 101) { //本次临店的问题
            self.segmentIndex = 2;
            
            self.segLeftImgV.image = [UIImage imageNamed:@"筛选btn_左_n.png"];
            self.segLeftLbl.textColor = CustomRed;
            self.segRightImgV.image = [UIImage imageNamed:@"筛选btn_右_p.png"];
            self.segRightLbl.textColor = [UIColor whiteColor];
            
            NSString *piciNum = [self.applyInfo objectForKeyOrNil:@"pc"];
            if ([piciNum length] > 0) {
                [self queryThisTimeStoreProblemByPici:piciNum];
            }
        }
        
        self.isRefreshing = YES;
    }
}

//获取历史未完成问题
- (void)getHistoryProblemList {
    UserInfo *user = [UserInfo instance];
    NSInteger roleFlag = [[user.info objectForKeyOrNil:@"ryfl"] integerValue];
    
    NSString *gonghao = @"";
    if (roleFlag == 2) { //领导
        gonghao = [self.applyInfo objectForKeyOrNil:@"gh"];
    } else if (roleFlag == 3) {
        gonghao = [user.info objectForKeyOrNil:@"gh"];
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           gonghao,@"gh", nil];
    [self.networkManager requestWithMethod:history parameter:param delegate:self];
    [self.HUD show:YES];
}

//获取本次临店的问题
- (void)queryThisTimeStoreProblemByPici:(NSString *)pc {
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                           pc,@"pc", nil];
    UserInfo *user = [UserInfo instance];
    NSInteger roleFlag = [[user.info objectForKeyOrNil:@"ryfl"] integerValue];
    if (roleFlag == 2) { //领导
        NSString *gonghao = [self.applyInfo objectForKeyOrNil:@"gh"];
        [param setObject:gonghao forKey:@"gh"];
//        [self.networkManager requestWithMethod:showThisQuestionsOnCommit parameter:param delegate:self];
        [self.networkManager requestWithMethod:showThisQuestions parameter:param delegate:self];
    } else if (roleFlag == 3) {
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        [param setObject:gonghao forKey:@"gh"];
        [self.networkManager requestWithMethod:showThisQuestions parameter:param delegate:self];
    }
    
    [self.HUD show:YES];
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if (methodId == showThisQuestions || methodId == showThisQuestionsOnCommit) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                self.problemList = [NSMutableArray array];
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *problems = [dataObject objectForKeyOrNil:@"question"];
                        if (![problems isKindOfClass:[NSNull class]] && [problems count] > 0) {
                            [self.problemList  addObjectsFromArray:problems];
                        }
                    }
                }
                
                [self.tableView reloadData];
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    msg = @"本次临店问题获取失败，请稍后重试";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
    } else if (methodId == history) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                [self.historyProblemList removeAllObjects];
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *problems = [dataObject objectForKeyOrNil:@"wtbs"];
                        if (![problems isKindOfClass:[NSNull class]] && [problems count] > 0) {
                            [self.historyProblemList  addObjectsFromArray:problems];
                        }
                    }
                }
                
                [self.tableView reloadData];
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    msg = @"历史未完成问题获取失败，请稍后重试";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
    } else if (methodId == generateReport) { //提交出差报告
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) { //请求成功
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        int resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                        if (resultCode == 1) { //提交成功
                            
                            NSString *msg = @"";
                            msg = @"出差报告提交成功！";
                            
//                            MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                            overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                            overlay.detailViewMode = MTDetailViewModeDetailText;
//                            overlay.delegate = nil;
//                            overlay.progress = 0.0;
//                            [overlay postFinishMessage:msg duration:1.6 animated:YES];
//                            overlay.progress = 1.8;
                            
                            [self showAlertViewWithMessage:msg];
                            
                            [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                        } else {
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                            message:@"出差报告提交失败，请重试"
                                                                           delegate:nil
                                                                  cancelButtonTitle:@"确定"
                                                                  otherButtonTitles:nil];
                            [alert show];
                        }
                    } else {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                        message:@"出差报告提交失败，请重试"
                                                                       delegate:nil
                                                              cancelButtonTitle:@"确定"
                                                              otherButtonTitles:nil];
                        [alert show];
                    }
                }
            }
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            if (methodId == showThisQuestions) {
                msg = @"本次临店问题获取失败，请稍后重试";
            } else if (methodId == history) {
                msg = @"历史未完成问题获取失败，请稍后重试";
            }
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.segmentIndex == 1) {
        return [self.historyProblemList count];
    } else {
        return [self.problemList count];
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"DudaoProblemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    UILabel *label1 = (UILabel *)[cell.contentView viewWithTag:100];
    UILabel *label2 = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *label3 = (UILabel *)[cell.contentView viewWithTag:102];
    UIButton *btn = (UIButton *)[cell.contentView viewWithTag:103];
    
    NSInteger row = indexPath.row;
    
    NSMutableArray *data = nil;
    if (self.segmentIndex == 1) {
        data = [NSMutableArray arrayWithArray:self.historyProblemList];
    } else {
        data = [NSMutableArray arrayWithArray:self.problemList];
    }
    if ([data count] > row) {
        NSDictionary *cellData = [data objectAtIndex:row];
        
        NSString *name = [cellData objectForKeyOrNil:@"jxsmc"]; //经销商名称
        NSString *code = [cellData objectForKeyOrNil:@"jxsdm"]; //经销商代码
        NSString *description = [cellData objectForKeyOrNil:@"wtms"]; //问题描述
        NSString *endtime = [cellData objectForKeyOrNil:@"sjz"]; //截止时间
        
        label1.text = name;
        label2.text = code;
        label3.text = description;
        
        if ([endtime length] == 0) {
            endtime = @"截止时间";
        }
        [btn setTitle:endtime forState:UIControlStateNormal];
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    NSMutableArray *data = nil;
    if (self.segmentIndex == 1) {
        data = [NSMutableArray arrayWithArray:self.historyProblemList];
    } else {
        data = [NSMutableArray arrayWithArray:self.problemList];
    }
    
    HistoryProblemDetailViewController *detailVC = (HistoryProblemDetailViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"HistoryProblemDetail"];
    if ([data count] > row) {
        NSDictionary *cellData = [data objectAtIndex:row];
        detailVC.problemInfo = cellData;
    }
    detailVC.showRightItem = NO;
    if (self.fromLeader) {
        detailVC.canEditTime = NO;
    } else {
        detailVC.canEditTime = YES;
    }
    [self.navigationController pushViewController:detailVC animated:YES];
}

@end
